package com.leyou.trade.service.impl;

import com.leyou.common.exception.LyException;
import com.leyou.trade.entity.Order;
import com.leyou.trade.service.OrderService;
import com.leyou.trade.service.PayService;
import com.leyou.trade.utils.PayHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private PayHelper payHelper;

    @Autowired
    private OrderService orderService;

    /**
     * 获取付款二维码地址
     *
     * @param id
     * @return
     */
    @Override
    public String createPayUrl(Long id) {
        Order order = this.orderService.getById(id);
        String s = payHelper.getPayUrl(id, 1L/*order.getActualFee()*/, "黑马");
        return s;
    }

    /**
     * 支付回调
     *
     * @param notifyParm
     */
    @Override
    public void handlerNotify(Map<String, String> notifyParm) {
        payHelper.checkResultCode(notifyParm);
        payHelper.checkResultCode(notifyParm);
        payHelper.checkResponseSignature(notifyParm);

        String out_trade_no = notifyParm.get("out_trade_no");
        String total_fee = notifyParm.get("total_fee");

        if (StringUtils.isEmpty(out_trade_no) || StringUtils.isEmpty(total_fee)) {
            throw new LyException(400, "支付错误");
        }
        Order order = this.orderService.getById(Long.valueOf(out_trade_no));

        Long orderId = order.getOrderId();
        //状态为未付款
        if (order.getStatus() == 1) {
            if (Long.valueOf(total_fee).equals(1) /*order.getActualFee()*/) {
                throw new LyException(400, "支付金额错误");
            }
            //防止网络抖动 重复修改
            this.orderService.update()
                    .set("status", 2)
                    .set("pay_time", new Date())
                    .eq("order_id",orderId)
                    .eq("status",1).update();
        }


    }


}
